<?php

namespace pos\services\order;

use common\models\order\OrderModel;
use pos\extensions\ApiBaseService;
use pos\services\wechat\MiniPayService;
use common\models\user\UserModel;
use pos\services\order\BalanceService;

/**
 * 支付服务
 */
class PaymentService extends ApiBaseService
{

    /**
     * 订单支付
     * @param array $params 请求参数
     * * */
    public static function payment($params)
    {
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $headers = \Yii::$app->getRequest()->getHeaders();
            $device = $headers->get('deviceId');
            if (empty($device)) {
                throw new \Exception('收银机号异常');
            }
            $order = OrderModel::findOne(['order_sn' => $params['order_sn'], 'device' => $device]);
            if (empty($order)) {
                throw new \Exception('订单信息异常');
            }
            if ($order['state'] != OrderModel::STATE_WAIT_PAY) {
                throw new \Exception('订单状态异常');
            }
            $res = [];
            if($params['pay_way'] == OrderModel::PAY_WEIXIN_MINI) {
                // 微信支付
                if($params['type'] == 1 && !empty($params['auth_code'])) {
                    $res =  MiniPayService::mainScanCustomer($order, $params['auth_code']);
                } else if($params['type'] == 2) {
                    $res = MiniPayService::customerScanMain($order, $params);
                } else {
                    throw new \Exception('参数异常');
                }
            } else if($params['pay_way'] == OrderModel::PAY_CASHE) {
                // 现金支付
                $pickupNumber = str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);
                // 现金支付：直接修改订单状态
                $order->setAttributes(['state' => OrderModel::STATE_RECEIVED,'pay_time' => date('Y-m-d H:i:s'), 'pickup_no' => $pickupNumber], false);
            } else if($params['pay_way'] == OrderModel::PAY_BALANCE) {
                // 余额支付
                // 判断用户——获取用户余额信息
                if(empty($order['user_id'])) {
                    throw new \Exception('请先查找用户，再进行余额支付');
                }
                $res = BalanceService::payment($order, ['id'=> $order['user_id']]);
            } else {
                throw new \Exception('请选择支付方式');
            }

            // 更新支付方式
            $order->setAttributes(['pay_way' => $params['pay_way']], false);
            if (empty($order->save())) {
                throw new \Exception('更新异常');
            }

            $transaction->commit();
            return empty($res) ? self::jsonSuccess([]) : $res;
        } catch (\Exception $exc) {
            $transaction->rollBack();
            \Yii::$app->writeLog->log('/api/pay', '支付回调结果', ['message' => $exc->getMessage()], 'INFO');
            return self::jsonError($exc->getMessage());
        }
    }

    /**
     * 支付回调
     * **/
    public static function callback($params)
    {
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $order_sn = $params['order_sn'];
            // 查找订单信息
            $order = OrderModel::findOne(['order_sn' => $order_sn]);
            if (empty($order)) {
                throw new \Exception('订单信息异常');
            }
            // 手动触发支付查询
            if (isset($params['query']) && $params['query'] == 1 && ($order['state'] == OrderModel::STATE_WAIT_DELIVERY || $order['state'] == OrderModel::STATE_RECEIVED)) {
                return self::jsonSuccess($order);
            }
            if ($order['state'] != OrderModel::STATE_WAIT_PAY) {
                throw new \Exception('订单状态异常');
            }
            //查询
            $query = MiniPayService::query($order_sn);
            if ($query['code'] == 1) {
                throw new \Exception($query['message']);
            }
            // 更新订单状态
            $pickupNumber = str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);
            // 更新订单状态
            $order->setAttributes(['state' => OrderModel::STATE_RECEIVED, 'pay_time' => date('Y-m-d H:i:s'), 'pickup_no' => $pickupNumber], false);
            if (empty($order->save())) {
                throw new \Exception('更新异常');
            }
            $order['state'] = OrderModel::STATE_RECEIVED;
            $transaction->commit();
            return self::jsonSuccess($order);
        } catch (\Exception $exc) {
            $transaction->rollBack();
            \Yii::$app->writeLog->log('/api/callback', '支付回调异常', ['params' => $params, 'message' => $exc->getMessage(), 'line' => $exc->getLine()], 'INFO');
            return self::jsonError($exc->getMessage());
        }
    }


    /**
     * 支付确认
     * **/
    public static function confirm($params)
    {
        $params['query'] = 1;
        return self::callback($params);
    }

}
